<?php
session_start();
//连接数据库
/**
try {
    $db = new PDO('mysql:dbname=books;host=127.0.0.1','root','123456');

    $data[':username']=$_POST['username'];
    $data[':password']=$_POST['password'];
    $search = $db->prepare('select * from admin where username=:username and password=:password');
    $search->execute($data);
    if($search->fetch()){
        echo "<script> alert('登录成功!'); location.href='../index.php';</script>";
        $_SESSION['user']= $data[':username'];
    }else{
        echo "<script> alert('登录失败!'); location.href='../login.php';</script>";
    }
**/
try {
    function success(){
        $result=[
            'error' => 0,
            'message' => '成功'
        ];
        return json_encode($result);
    }
    function error($mag){
        $data = [
            'error' => 1,
            'message' => $mag
        ];
        return json_encode($data);
    }
    $db = new PDO('mysql:dbname=books;host=127.0.0.1','root','123456');
    $data[':username']=$_POST['username'];
    $data[':password']=$_POST['password'];
    $search = $db->prepare('select * from admin where username=:username and password=:password');
    $search->execute([
        ':username'=> $_POST['username'],
        ':password'=> $_POST['password']
    ]);
    $re=$search->fetch();
    if(empty($_POST['username'])){
        die(error('用户名不能为空'));
    }
    if(empty($_POST['password'])){
        die(error('密码不能为空'));
    }
    if($_POST['username']!= $re['username']){
        die(error('用户名不存在'));
    }
    if($_POST['password']!=$re['password']){
        die(error('密码不正确'));
    }
    $_SESSION['user']= $data[':username'];
    echo success();
} catch (PDOException $e) {
    echo 'Connection failed';
}